<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";

const today = new Date().toISOString().split("T")[0];

const formData = ref({
  planName: "",
  assessmentCycle: "",
  departmentId: null,
  startDate: "",
  endDate: "",
});

const departments = ref([]);

onMounted(async () => {
  try {
    const res = await axios.get("http://127.0.0.1:8080/admin/department/getAll", {
      headers: {
        token: localStorage.getItem("token"),
      },
    });
    const data = res.data.data;
    departments.value = Array.isArray(data) ? data.filter(Boolean) : [];
  } catch (e) {
    console.error(e);
  }
});

const indicators = ref([]);

const totalWeight = computed(() => {
  return indicators.value.reduce((sum, item) => sum + (item.weight || 0), 0);
});

const addIndicator = () => {
  indicators.value.push({
    indicatorName: "",
    indicatorType: "",
    scoringStandard: "",
    weight: 0,
  });
};

const removeIndicator = (index) => {
  indicators.value.splice(index, 1);
};

const handleSubmit = async () => {
  if (!formData.value.planName) {
    ElMessage.error("请输入考核计划名称");
    return;
  }
  if (!formData.value.assessmentCycle) {
    ElMessage.error("请选择考核周期");
    return;
  }
  if (!formData.value.departmentId) {
    ElMessage.error("请选择部门");
    return;
  }
  if (!formData.value.startDate || !formData.value.endDate) {
    ElMessage.error("请选择计划起止时间");
    return;
  }
  if (formData.value.startDate > formData.value.endDate) {
    ElMessage.error("计划开始时间不能晚于计划结束时间");
    return;
  }
  if (indicators.value.length === 0) {
    ElMessage.error("请至少添加一个考核指标");
    return;
  }
  if (totalWeight.value !== 100) {
    ElMessage.error("指标权重总和必须为100%");
    return;
  }

  const planVo = {
    ...formData.value,
    indicators: indicators.value.map((item) => ({
      indicatorName: item.indicatorName,
      indicatorType: item.indicatorType,
      scoringStandard: item.scoringStandard,
      weight: item.weight,
    })),
  };


  try {
    const res = await axios.post("http://127.0.0.1:8080/admin/assessment/publish",planVo,{
      headers: {
        token: localStorage.getItem("token"),
      },
    });
    if (res.data.code == 200) {
      ElMessage.success("保存成功")
      handleCancel(); // 新增这一行
    }else{
      ElMessage.error("系统错误")
    }
  } catch (e) {
    console.error(e);
  }
};

const handleCancel = () => {
  formData.value = {
    planName: "",
    assessmentCycle: "",
    departmentId: null,
    startDate: "",
    endDate: "",
  };
  indicators.value = [];
};

const filterMethod = (query, option) => {
  return option.label.toLowerCase().includes(query.toLowerCase());
};
</script>

<template>
  <div class="min-h-screen bg-gray-50 py-8 px-4">
    <div
      class="max-w-5xl mx-auto bg-white rounded-lg shadow-sm p-8"
      style="max-height: 80vh; overflow-y: auto"
    >
      <h1 class="text-2xl font-bold mb-8">添加考核计划</h1>

      <!-- 基本信息表单 -->
      <div class="space-y-6 mb-8">
        <div class="grid grid-cols-2 gap-6">
          <a-form-item label="考核计划名称" required>
            <a-input v-model:value="formData.planName" placeholder="请输入考核计划名称" />
          </a-form-item>

          <a-form-item label="考核周期" required>
            <el-radio-group v-model="formData.assessmentCycle" style="width: 100%">
              <el-radio label="monthly">月度考核</el-radio>
              <el-radio label="quarterly">季度考核</el-radio>
              <el-radio label="yearly">年度考核</el-radio>
            </el-radio-group>
          </a-form-item>

          <a-form-item label="部门" required>
            <el-select
              v-model="formData.departmentId"
              placeholder="请选择部门"
              :filter-method="filterMethod"
              class="w-full"
              teleported
              style="width: 100%"
              popper-class="custom-select-dropdown"
              placement="bottom-start"
            >
              <el-option
                v-for="d in departments"
                :key="d.departmentId"
                :label="d.departmentName"
                :value="d.departmentId"
              />
            </el-select>
          </a-form-item>

          <a-form-item label="计划开始时间" required>
            <el-date-picker
              v-model="formData.startDate"
              type="date"
              placeholder="请选择开始日期"
              :disabled-date="(date) => date < new Date(today)"
              style="width: 100%"
            />
          </a-form-item>

          <a-form-item label="计划结束时间" required>
            <el-date-picker
              v-model="formData.endDate"
              type="date"
              placeholder="请选择结束日期"
              :disabled-date="(date) => date < new Date(formData.startDate)"
              style="width: 100%"
            />
          </a-form-item>
        </div>
      </div>

      <!-- 考核指标区域 -->
      <div class="mb-8">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-xl font-medium">考核指标</h2>
          <a-button type="primary" @click="addIndicator" class="!rounded-button">
            <template #icon><PlusOutlined /></template>
            添加指标
          </a-button>
        </div>

        <div class="space-y-4">
          <div
            v-for="(indicator, index) in indicators"
            :key="index"
            class="p-6 bg-gray-50 rounded-lg border border-gray-200"
          >
            <div class="grid grid-cols-2 gap-6">
              <a-form-item label="指标名称" required>
                <a-input
                  v-model:value="indicator.indicatorName"
                  placeholder="请输入指标名称"
                />
              </a-form-item>

              <a-form-item label="指标类型" required>
                <el-radio-group v-model="indicator.indicatorType" style="width: 100%">
                  <el-radio label="quantity">数量指标</el-radio>
                  <el-radio label="quality">质量指标</el-radio>
                  <el-radio label="efficiency">效率指标</el-radio>
                </el-radio-group>
              </a-form-item>

              <a-form-item label="评分标准" required class="col-span-2">
                <a-textarea
                  v-model:value="indicator.scoringStandard"
                  :rows="3"
                  placeholder="请输入评分标准描述"
                />
              </a-form-item>

              <a-form-item label="指标权重" required>
                <a-input-number
                  v-model:value="indicator.weight"
                  :min="0"
                  :max="100"
                  :formatter="(value) => `${value}%`"
                  :parser="(value) => value.replace('%', '')"
                  style="width: 100%"
                />
              </a-form-item>

              <div class="flex items-center justify-end">
                <a-button danger @click="removeIndicator(index)" class="!rounded-button">
                  <template #icon><DeleteOutlined /></template>
                  删除
                </a-button>
              </div>
            </div>
          </div>
        </div>

        <div class="mt-4 text-right text-gray-600">总权重：{{ totalWeight }}%</div>
      </div>

      <!-- 底部按钮 -->
      <div class="flex justify-center space-x-4">
        <a-button
          type="primary"
          size="large"
          @click="handleSubmit"
          class="!rounded-button"
        >
          保存
        </a-button>
        <a-button size="large" @click="handleCancel" class="!rounded-button">
          取消
        </a-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
:deep(.ant-input-number-handler-wrap) {
  display: none;
}
.custom-select-dropdown {
  z-index: 99999 !important;
}
</style>
